package edu.hzit.data.service.impl;

import edu.hzit.data.entity.User;
import edu.hzit.data.mapper.UserMapper;
import edu.hzit.data.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
     BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
    @Override
    public User login(String phone, String password) {
        //根据手机号查询用户信息
        User user = userMapper.selectByPhone(phone);
        //那数据库加密后的密码和登录时的密码进行比较
        boolean matches = passwordEncoder.matches(password, user.getPassword());
        if (matches){
            //密码一致，返回用户对象
            return user;
        }
       return null;
    }

    @Override
    public int insert(User user) {
        //对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userMapper.insert(user);
    }

    @Override
    public List<User> loadList() {
        return userMapper.loadList();
    }

    @Override
    public User selectById(int userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public User selectByPhone(String phone) {
        return userMapper.selectByPhone(phone);
    }

    @Override
    public int delete(int userId) {
        return userMapper.delete(userId);
    }

    @Override
    public int update(User user) {
        return userMapper.update(user);
    }

    @Override
    public int updPwd(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userMapper.updPwd(user);
    }

    @Override
    public int updPassword(@Param("userId") int userId,@Param("oldPwd") String oldPwd, @Param("newPwd") String newPwd) {
        User user = userMapper.selectById(userId);
        //拿旧密码和数据库的密码进行对比
        boolean matches = passwordEncoder.matches(oldPwd, user.getPassword());
        if (matches){
            //如果一致，对新密码加密并写入数据库
            String newPassword= passwordEncoder.encode(newPwd);
            return userMapper.updPassword(userId, newPassword);
        }
       return 0;
    }

}
